/*!
 * Amit kumar srivastava    
 * amee9451@gmail.com
 */
function setcookies(c_name, value, exdays, extime) {
    if (extime == "" || extime == null || typeof (extime) == "undefined")
        extime = false;
    var exdate = new Date();
    if (extime) {
        exdate.setMinutes(exdate.getMinutes() + extime);
    }
    else {
        exdate.setDate(exdate.getDate() + exdays);
    }

    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()) + "; path=/";
    document.cookie = c_name + "=" + c_value;
}

function getcookies(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++)
    {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+jQuery/g, "");
        if (x == c_name)
        {
            return unescape(y);
        }
    }
}

jQuery(function($) {

    $.ajaxSetup({
        async: false
    });

    var availableTags = ['Adipur', 'Adoor', 'Agartala', 'Agra', 'Ahmedabad', 'Ahmednagar', 'Ajmer', 'Akola', 'Aligarh', 'Allahabad', 'Allepey', 'Alwar', 'Amayannoor', 'Ambala', 'Ambikapur', 'Amloh', 'Amravati', 'Amreli', 'Amritsar', 'Anand', 'Anantapur', 'Andul', 'Angul', 'Anjar', 'Ankleshwar', 'Arambagh', 'Asansol', 'Attingal', 'Attur', 'Aurangabad', 'Baddi', 'Bagalkot', 'Baghapurana', 'Bahadurgarh', 'Balasore', 'Bambolim', 'BANASWARA', 'Banga', 'Bangalore', 'Barabanki', 'Baramulla', 'Bardez', 'Bardhamann', 'Bardoli', 'Bareily', 'Barmer', 'Barnala', 'Baroda', 'Bassi Pathana', 'Batala', 'Bavla', 'Begowal', 'Begusarai', 'Behraich', 'Belgaum', 'Beowar', 'Betul', 'Bhadohi', 'Bhagalpur', 'Bharatpur', 'Bharuch', 'Bhatapara', 'Bhatinda', 'Bhavnagar', 'Bhilai', 'Bhilwara', 'Bhiwadi', 'Bhiwani', 'Bhopal', 'Bhubaneshwar', 'Bhuj', 'Bhusaval', 'Bidar', 'Bijnor', 'Bikaner', 'Bilaspur', 'Billimora', 'Boisar', 'Bokaro', 'Borsad', 'Botad', 'Brahmapur', 'Budhalada', 'Bulandsaher', 'Burdwan', 'Calangute', 'Calicut', 'Candolim', 'Chagnacherry', 'Chalakudy', 'Chandannagar', 'Chandigarh', 'Chandrapur', 'Chenganur', 'Chennai', 'Chennamangalam', 'Cheppad', 'Cherthala', 'Chicalim', 'Chidhambaram', 'Chinchinim', 'Chindwara', 'Chinnamiram', 'CHITTORGARH', 'Coimbatore', 'Contai', 'Coochbehar', 'Cuddalore', 'Cuddapah', 'Curchorum', 'Cuttack', 'Dadra', 'Dadri', 'Dahej', 'Dahod', 'Daman', 'Damanjodi', 'Damoh', 'Dankuni', 'Darbhanga', 'Darjeeling', 'Dausa', 'Davangere', 'Deesa', 'Dehradun', 'Delhi', 'Deogarh', 'Deoria', 'Dera Bassi', 'Dewas', 'Dhamtari', 'Dhanbad', 'Dhankuni', 'Dhar', 'Dharmaj', 'Dharmapuri', 'Dharmshala', 'Dholpur', 'Dhule', 'DIBRUGARH', 'Durg', 'Durgapur', 'Ernakulam', 'Erode', 'Etha', 'Faizabad', 'Faridabad', 'Faridkot', 'Fatehabad', 'Fatehgarh Sahib', 'Fazilka', 'Ferozepur', 'Firozabad', 'Gadarpur', 'Gandhidham', 'Gandhinagar', 'Gangtok', 'Garhshankar', 'Gaya', 'Ghaziabad', 'Gidderabha', 'Giridih', 'Goa', 'Godhra', 'Gondal', 'Gondia', 'Gorakhpur', 'Goraya', 'Gudur', 'Gulbarga', 'Guna', 'Guntur', 'Gurdaspur', 'Gurgaon', 'Guwahati', 'Gwalior', 'Habra', 'Hajipur', 'Haldia', 'Haldwani', 'Halol', 'Hamirpur', 'Hanumangarh', 'Hapur', 'Harda', 'Hardoi', 'Haridwar', 'Hassan', 'Hathras', 'Hazaribagh', 'Himatnagar', 'Hindupur', 'Hissar', 'Hoshiarpur', 'Hosur', 'Howrah', 'Hubli', 'Hyderabad', 'Idar', 'Indore', 'Itarsi', 'Jabalpur', 'Jagadhari', 'Jagdispur', 'Jagraon', 'Jaipur', 'Jajpur', 'Jakhal', 'Jalandhar', 'Jalgaon', 'Jalna', 'Jammu', 'Jamnagar', 'Jamshedpur', 'Jaunpur', 'Jetalsar', 'Jetpur', 'Jeypore', 'Jhajjar', 'Jhansi', 'Jharsuguda', 'Jhunjhunu', 'Jind', 'Jodhpur', 'Jorhat', 'Jowai', 'Joya', 'Junagadh', 'Kadi', 'Kaithal', 'Kakinada', 'Kalka', 'Kalol', 'Kalyan', 'Kalyani', 'Kangra', 'Kanhangad', 'Kannur', 'Kanpur', 'Kapadvanj', 'Kapurthala', 'Karad', 'Karim Nagar', 'Karnal', 'Karunagapally', 'Karur', 'Kasaragod', 'Kashipur', 'Katni', 'Keonjhar', 'Keshod', 'Kesrisinghpur', 'Khamgoan', 'Khandwa', 'Khanna', 'Kharagpur', 'Kharar', 'Khargone', 'Khurja', 'Kochi', 'Koduvayur', 'Kolhapur', 'Kolkatta', 'Kollam', 'Korba', 'Kosamba', 'Kosi Kalan', 'Kota', 'Kothagudem', 'Kotiakapura', 'Kotkapura', 'Kottakkal', 'Kottayam', 'Kundli', 'Kurali', 'Kurnool', 'Kurukshetra', 'Kutch', 'Kuthannur', 'Ladwa', 'Latur', 'Lonavala', 'Lucknow', 'Ludhiana', 'Machhiwara', 'Madurai', 'Mahilpur', 'Mahuva', 'Majorda', 'Malerkotla', 'Malout', 'Manavadar', 'Mancherial', 'Mandi', 'Mandigobindgarh', 'Mandsaur', 'Manesar', 'Mangalore', 'Manipal', 'Manjeri', 'Mansa', 'Mapusa', 'Margao', 'Mathura', 'Mavelikara', 'Meerut', 'Mehbubnagar', 'Mehsana', 'Modasa', 'Modinagar', 'Moga', 'Mohali', 'Moovattupuzha', 'Moradabad', 'Morinda', 'Morvi', 'Mukerian', 'Muktsar', 'Mumbai', 'Murshidabad', 'Muzaffarpur', 'Muzzafarnagar', 'Mysore', 'Nabha', 'Nadiad', 'Nagercoil', 'Nagpur', 'Nainital', 'Nakodar', 'Namakkal', 'Nanded', 'Nandyal', 'Narasaraopet', 'Narnaul', 'Nashik', 'Navi Mumbai', 'Navsari', 'Nawanshar', 'Naya Nangal', 'Neemrana', 'Neemuch', 'Nellore', 'New Delhi', 'Nihar', 'Nissing', 'Nizamabad', 'Noida', 'Noonmati', 'Nurmahal', 'Ongole', 'Ooty', 'Pachalam', 'Pala', 'Palakkad', 'Palanpur', 'Palghar', 'Pali', 'Pallakad', 'Palwal', 'Panchkula', 'Panipat', 'Panjim', 'Patan', 'Pathanamthitta', 'Pathankot', 'Patiala', 'Patna', 'Pazhayannur', 'Pehowa', 'Perinthalmanna', 'Perumbavoor', 'Petlad', 'Phagwara', 'Philkuwa', 'Phillaur', 'Pilibanga', 'Pinjore', 'Pipariya', 'Pollachi', 'Ponda', 'Pondicherry', 'Porbandar', 'Porvorim', 'Pratapgarh', 'Prodattur', 'PUDUKOTTAI', 'Pune', 'Puri', 'Puthenchira', 'Puttaparthi', 'Quepem', 'Raibareilly', 'Raichur', 'Raigarh', 'Raipur', 'Rajahmundry', 'Rajkot', 'Rajnandgaon', 'Rajpura', 'Rajsmand', 'RAMANATTUKARA', 'Ramgarh', 'Ramgarh Cant.', 'Rampura phul', 'Ranchi', 'Ratia', 'Ratlam', 'Ratnagiri', 'Rewa', 'Rewari', 'Rohtak', 'Roorkee', 'Ropar', 'Rourkela', 'Rudrapur', 'S. L. Puram', 'Sagar', 'Saharanpur', 'Sahibabad', 'Sahnewal', 'salem', 'Samana', 'Sambalpur', 'Samrala', 'Sanand', 'Sangli', 'Sangrur', 'Sardulgarh', 'Satara', 'Satna', 'Secunderabad', 'Shahjahanpur', 'Shahpura', 'Shillong', 'Shimla', 'Shimoga', 'Shivpuri', 'Shrirampur', 'Siddhpur', 'Sihor', 'Sikar', 'Silchar', 'Siliguri', 'Silvassa', 'Sindhnur', 'Sirsa', 'Sitapur', 'Sitarganj', 'Siwan', 'Sohna', 'Solan', 'Solapur', 'Sonepat', 'South Parur', 'Sriganganagar', 'Srikakulam', 'Srinagar', 'Sujalpur', 'Sultanpur', 'Surat', 'Surendranagar', 'Sussari', 'Tanda', 'Tanuku', 'Tarntaran', 'Tezpur', 'Thalaserry', 'Thane', 'Thangadh', 'Thanjavur', 'Theni', 'Thiruvalla', 'Thiruvannamalai', 'Thodupuzha', 'Thumboor', 'Tinsukia', 'Tirunelveli', 'Tirupati', 'Tirupur', 'Tirur', 'Tiruvallur', 'Tiruvarur', 'Tohana', 'Trichur', 'Trichy', 'Trivandrum', 'Tuticorin', 'Udaipur', 'Udipi', 'Ujjain', 'Ultadanga', 'Umbergoan', 'Una', 'Unjha', 'V allabh Vidyanagar', 'Vadagara', 'VADAKKENADA', 'Valsad', 'Vapi', 'Varanasi', 'Varca', 'Vasai', 'Vasco', 'Veliyanad', 'Vellore', 'Veraval', 'Vidisha', 'Vijapur', 'Vijaywada', 'Villupuram', 'Virudhunagar', 'Visnagar', 'Viyyoor', 'Vizag', 'Vrindavan', 'Vyara', 'Wankaner', 'Wardha', 'Warrangal', 'Yamunanagar', 'Yavatmal', 'Zira', 'Zirakpur'];
    $("#uCity").autocomplete({source: availableTags});

    // validate url
    function checkUrl(value) {
        return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
    }
    // validate email
    function checkEmail(value) {
        return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
    }

    function isValidYoutubeOrVimeoUrl(url) {
        var success = false;
        if (url.match('http://(www.)?youtube|youtu\.be')) {
            success = true;
        } else if (url.match('http://(www.)?vimeo\.com')) {
            success = true;
        }
        return success;
    }

    function isValidYoutubeUrl(url) {
        var success = false;
        if (url.match('http://(www.)?youtube|youtu\.be')) {
            success = true;
        }
        return success;
    }

    function whiteSpaceCheck() {
        var pattren = new RegExp(" ");
        var pattren2 = new RegExp(/[^a-zA-Z 0-9 . _]+/g);
        if (pattren.exec($('input[name=uLogin]').val()) != null || pattren2.exec($('input[name=uLogin]').val()) != null) {
            var newval = $('input[name=uLogin]').val().replace(" ", "").replace(/[^a-zA-Z 0-9 . _]+/g, '');
            $('input[name=uLogin]').val(newval).focus();
            return false;
        }
    }
    function isValidLogin(login) {
        var pattern = new RegExp(/^[a-zA-Z0-9-_]+$/);
        return pattern.test(login);
    }
    /*
     * Request invite, login and forgot password area 
     */
    // forgot user password form action
    $('a#forgetPassword').on('click', function() {
        $( 'div#userForgotPassDiv, div#forgotMesageSentDiv' ).hide();

        $('input[name=forgotEmailOrLogin]').next().html('').hide();
        if ($('#userForgotPassDiv').is(":visible")) {
            $('#userForgotPassDiv').fadeOut(500);
        } else {
            $('#userForgotPassDiv').fadeIn(1000);
        }
    });
    /*
     * Forgot user password check
     */
    $('input[name=forgotPassBtn]').click(function() {
        $('input[name=forgotEmailOrLogin]').next().html('').hide();
        var forgotEmailOrLogin = $.trim($('input[name=forgotEmailOrLogin]').val());
        if (forgotEmailOrLogin == '') {
            $('input[name=forgotEmailOrLogin]').focus();
            $('input[name=forgotEmailOrLogin]').next().html($('input[name=forgotEmailOrLogin]').attr('rel')).show();
            return false;
        }
        $.ajax({
            url: '/ajax/invite/',
            type: 'post',
            data: {method: 'forgotPasswordChk', forgotEmailOrLogin: forgotEmailOrLogin},
            success: function(resp) {
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    $('input[name=forgotEmailOrLogin]').next().html($.trim(respObj.message)).show();
                    $('input[name=forgotEmailOrLogin]').focus();
                    return false;
                } else {
                    $( 'div#userForgotPassDiv' ).fadeOut(500);
                    $( 'div#forgotMesageSentDiv' ).fadeIn(500);
                    setTimeout( function() {
                        $( 'div#forgotMesageSentDiv' ).fadeOut(500);
                    }, 5000 );

                    //$('input[name=forgotEmailOrLogin]').next().html('Mail sent to you, Please check your inbox and reset your password !').show();
                    $('input[name=forgotEmailOrLogin]').val('');
                    //$( document ).trigger( 'closeIpbox' );
                    return false;
                }
            }
        });
    });

    // apply login action, just show login form and request for invite form
    $(document).on('click', 'a#applyLogin, a.applyLogin, a.headerLoginBtn', function() {
        //jQuery("html,body").animate({scrollTop: 0}, "slow");
        $('input[name=loginBtn]').removeClass('disabled');

        $('div.loginBoxBody').hide();
        $('#userForgotPassDiv').hide();
        $('#loginForm, #loginBox, #requestForInviteDiv', '#loginLightBox').show();
        $('#recommendedInviteNotedDiv, #generalInfoDiv, #yOurFrndsOnQyukiDiv, #inviteNotedDiv', '#loginLightBox').hide();
        $('#loginLightBox').ipbox();
        $('div.loginBoxBody').fadeIn(1500);
        // resize window
        $(window).trigger('resize');
        return false;
    });

    // login the user to the system via ajax submit
    $(document).on('click', 'input[name=loginBtn]', function() {
        $this = $(this);
        if ($this.hasClass('disabled')) {
            console.log('Please wait...');
            return false;
        }
        $('.inputError', '#loginLightBox').html('').hide();

        $loginObj = $('input[name=login]', $this.parent().parent().parent());
        var login = $.trim($loginObj.val());
        if (login == '') {
            $loginObj.next().html('Please Enter Username/Email').show();
            $loginObj.focus();
            return false;
        }

        $pwdObj = $('input[name=password]', $this.parent().parent().parent());
        var password = $pwdObj.val();
        if (password == '') {
            $pwdObj.next().html('Please Enter Password').show();
            $pwdObj.focus();
            return false;
        }

        $this.addClass('disabled');
        $.ajax({
            url: '/ajax/admin/',
            type: 'post',
            data: {method: 'loginUser', login: login, password: password},
            success: function(resp) {
                $this.removeClass('disabled');
                // check save action
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    $this.parent().prev().html($.trim(respObj.msg)).show();
                } else {
                    $this.parent().prev().html('').hide();
                    window.location = respObj.redirectUrl;
                }
            }
        });

    });

    // on select of profile fill the subprofle
    $(document).on('change', 'select[name=profileId]', function() {
        $this = $(this);
        var profileId = $this.val();
        $('select[name=subProfileId] option').remove();
        $('<option value="0">Please wait...</option>').appendTo($('select[name=subProfileId]'));

        $.ajax({
            url: '/ajax/admin/',
            type: 'post',
            data: {method: 'getSubProfiles', id: profileId, type: 'first'},
            success: function(resp) {
                // check save action
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    alert(respObj.msg);
                    return false;
                } else {
                    eval('var respObj = ' + resp);
                    var profiles = respObj.profiles;
                    $('select[name=subProfileId] option').remove();
                    for (var n in profiles) {
                        $('<option value="' + profiles[n].value + '">' + profiles[n].text + '</option>').appendTo($('select[name=subProfileId]'));
                    }
                }
            }
        });
    });

    // check login availability
    $(document).on('keyup', 'input[name=uLogin]', function() {
        $('input[name=loginCheckStatus]').val(0);
        var $this = $(this);
        $this.next().html('').hide();
        whiteSpaceCheck();
        var userlogin = $this.val();
        if (userlogin == '' || userlogin.length < 4) {
            return false;
        }
        var draftUserId = $.trim($('input[name=draftUserId]').val());
        $.ajax({
            url: '/ajax/invite/',
            type: 'post',
            async: true,
            data: {method: 'loginCheck', login: userlogin, draftUserId: draftUserId},
            success: function(resp) {
                eval('var respObj = ' + resp);
                $('input[name=loginCheckStatus]').val($.trim(respObj.status));
                if (respObj.status) {

                    $.ajaxSetup({
                        async: false
                    });

                    //$this.val( '' );
                    $this.next().html($.trim(respObj.message)).show();
                } else {
                    $this.next().html('').hide();
                }
            }
        });
    });

    // check invite email availability
    $(document).on('blur', 'input[name=userEmail]', function() {
        $this = $(this);
        $this.next().html('').hide();
        $('input[name=inviteCheckStatus]').val(0);
        var inviteEmail = $this.val();
        if (inviteEmail == '') {
            $this.next().html($(this).attr('rel')).show();
            return false;
        } else if (!checkEmail(inviteEmail)) {
            $this.next().html('Invalid email entered !').show();
            return false;
        }
        // call ajax function to check availability of email
        $.ajax({
            url: '/ajax/invite/',
            type: 'post',
            data: {method: 'inviteAvailableCheck', email: inviteEmail},
            success: function(resp) {
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    $this.next().html($.trim(respObj.message)).show();
                } else {
                    //$this.next().html( $.trim( respObj.message ) ).attr( 'style', 'color:green;' );
                }
                $('input[name=inviteCheckStatus]').val($.trim(respObj.status));
            }
        });

    });

    $(document).on('blur', 'input[name=workUrl]', function() {
        $(this).next().html('').hide();
        workUrl = $.trim($(this).val());
        if (workUrl == '') {
            $(this).next().html($(this).attr('rel')).show();
            return false;
        } else {
            /*workUrl = workUrl.replace( 'http://', '' );
             workUrl = workUrl.replace( 'https://', '' );
             workUrl = workUrl.replace( 'www.', '' );
             workUrl = 'http://www.' + workUrl;*/

            workUrlArr = workUrl.split( '://' );
            if( workUrlArr.length == 1 ){
                workUrl = 'http://' + workUrlArr[ 0 ];
            }
            if (!checkUrl(workUrl)) {
                $(this).next().html('Please enter valid work URL!').show();
                return false;
            }
        }
    });

    // request for invite form action form
    $('input[name=requestInviteBtn]').click(function() {
        $this = $(this);
        if ($this.hasClass('disabled')) {
            console.log('Please wait...');
            return false;
        }

        firstName = $.trim($('input[name=firstName]').val());
        if (firstName == '') {
            $('input[name=firstName]').focus();
            $('input[name=firstName]').next().html($('input[name=firstName]').attr('rel')).show();
            return false;
        }
        lastName = $.trim($('input[name=lastName]').val());
        userEmail = $.trim($('input[name=userEmail]').val());
        if (userEmail == '') {
            $('input[name=userEmail]').next().html($('input[name=userEmail]').attr('rel')).show();
            $('input[name=userEmail]').focus();
            return false;
        } else if (!checkEmail(userEmail)) {
            $('input[name=userEmail]').focus();
            return false;
        } else if ($.trim($('input[name=inviteCheckStatus]').val()) == 1) {
            $('input[name=userEmail]').next().html('Email already exists !Plase try another !').show();
            $('input[name=userEmail]').focus();
            return false;
        }
        profileId = $('select[name=profileId]').val();
        if (profileId == '') {
            $('select[name=profileId]').focus();
            $('select[name=profileId]').next().html($('select[name=profileId]').attr('rel')).show();
            return false;
        }
        subProfileId = $('select[name=subProfileId]').val();

        workUrl = $('input[name=workUrl]').val();
        if (workUrl == '') {
            $('input[name=workUrl]').next().html($('input[name=workUrl]').attr('rel')).show();
            $('input[name=workUrl]').focus();
            return false;
        } else {
            /*workUrl = workUrl.replace( 'http://', '' );
             workUrl = workUrl.replace( 'https://', '' );
             workUrl = workUrl.replace( 'www.', '' );
             workUrl = 'http://www.' + workUrl;*/
            
            workUrlArr = workUrl.split( '://' );
            if( workUrlArr.length == 1 ){
                workUrl = 'http://' + workUrlArr[ 0 ];
            }
            if (!checkUrl(workUrl)) {
                $('input[name=workUrl]').val('').focus();
                $('input[name=workUrl]').next().html('Please enter valid work URL!').show();
                return false;
            }
        }
        $this.addClass('disabled');
        $.ajax({
            url: '/ajax/invite/',
            type: 'post',
            data: {
                method: 'userInvite', firstName: firstName, lastName: lastName,
                userEmail: userEmail, profile: profileId, subProfile: subProfileId,
                workUrl: workUrl
            },
            success: function(resp) {
                $this.removeClass('disabled');
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    alert($.trim(respObj.message));
                    return false;
                } else {
                    //$( 'span#lightboxHead' ).html( '' );
                    $('#loginBox, #generalInfoDiv, #yOurFrndsOnQyukiDiv, #loginForm, #requestForInviteDiv', '#loginLightBox').hide();

                    $('a.nimantranFb', '#inviteNotedDiv').attr('href', respObj.fbAuthUri);
                    $('a.nimantranIn', '#inviteNotedDiv').attr('href', respObj.lAuthUri);

                    $('#inviteNotedDiv', '#loginLightBox').show();
                    return false;
                }
            }
        });
    });

    // ask Qyuki user for recommendaton action
    $(document).on('click', 'a.requestForRecommend', function() {
        var userId = $(this).attr('rel');
        var inviteId = $(this).attr('inviteId');
        $.ajax({
            url: '/ajax/invite/',
            type: 'post',
            data: {method: 'inviteForRecommendByQkUser', userId: userId, inviteId: inviteId},
            success: function(resp) {
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    alert($.trim(respObj.message));
                    return false;
                } else {
                    history.pushState('', '', '/');
                    $('#inviteNotedDiv, #yOurFrndsOnQyukiDiv, #loginBox, #inviteNotedDiv #loginForm, #requestForInviteDiv', '#loginLightBox').hide();
                    $('#recommendedInviteNotedDiv', '#loginLightBox').fadeIn(500);
                    return false;
                }
            }
        });
        return false;
    });

    $(document).ready(function() {
        if (window.location.pathname == '/nv/login/') {
            $('div.loginBoxBody').hide();
            $('#userForgotPassDiv').hide();
            $('#loginForm, #loginBox, #requestForInviteDiv', '#loginLightBox').show();
            $('#recommendedInviteNotedDiv, #generalInfoDiv, #yOurFrndsOnQyukiDiv, #inviteNotedDiv', '#loginLightBox').hide();
            $('#loginLightBox').ipbox();
            $('div.loginBoxBody').fadeIn(1500);
            // resize window
            $(window).trigger('resize');
            return false;
        }


        /**
         * User Register Steps Code only this is needed else are done by ajax only.
         * @added 20 Feb 2014
         */
        var userRegisterStep = $.trim($('input[name=userRegisterStep]').val());
        if (userRegisterStep > 0) {
            $('#newUserRegisterStepsBody').hide();
            $('#newUserRegisterStepsLightBox').ipbox({modal: true});
            token = $.trim($('input[name=userRegisterToken]', '#newUserRegisterStepsLightBox').val());
            // call ajax file
            $.ajax({
                url: '/ajax/user-creation/',
                type: 'post',
                data: {method: 'userRegisterStep' + userRegisterStep, token: token},
                success: function(resp) {
                    // check save action
                    eval('var respObj = ' + resp);

                    if (respObj.status) {
                        $('#newUserRegisterStepsBody').fadeIn(1500);
                        $('#errorBox', '#newUserRegisterStepsBody').html($.trim(respObj.msg)).show();
                        return false;
                    } else {
                        $('#newUserRegisterStepsBody').html(respObj.html).fadeIn(1500);
                    }

                    // resize window
                    $(window).trigger('resize');
                }
            });
        }
        $(document).on('click', 'div.userCreationSteps', function() {
            var userRegisterStep = $(this).attr('rel');
            var userId = parseInt($(this).attr('data-rel'));
            token = $.trim($('input[name=userRegisterToken]', '#newUserRegisterStepsLightBox').val());

            if ('userRegisterStep2' != userRegisterStep && userId == 0) {
                return false;
            }

            if ($(this).hasClass('disabled')) {
                return false;
            }

            $('#newUserRegisterStepsBody').hide().html('Loading...');
            // call ajax file
            $.ajax({
                url: '/ajax/user-creation/',
                type: 'post',
                data: {method: userRegisterStep, token: token},
                success: function(resp) {
                    // check save action
                    eval('var respObj = ' + resp);
                    if (respObj.status) {
                        alert(respObj.msg);
                        return false;
                    } else {
                        $('#newUserRegisterStepsBody').html(respObj.html).fadeIn(1500);
                    }
                }
            });
        });

        $('.multiselect .dropup li.last').click(function() {
            $('.multiselect').toggleClass('open');
            $('.multiselect .dropvalue').removeClass('errorBorder');
            $('.multiselect .dropvalue').html($(this).html());
            $('.multiselect .dropvalue').attr('rel', $(this).attr('rel')).addClass('active');
        });

        // select the third level profile
        $('body').delegate('.multiselect .dropvalue', 'click', function() {
            $(this).parent().toggleClass('open');
        });

        $('body').delegate('.multiselect .dropup li.more', 'click', function() {
            $(this).parent('ul').children('li').removeClass('open');
            $(this).toggleClass('open');
        });

        $('body').delegate('.multiselect .dropup li.last', "click", function() {
            $(this).closest('li').removeClass('open');
            $(this).closest('.multiselect').removeClass('open');
            rel = $(this).attr('rel');
            $(this).closest('.multiselect').find('.dropvalue').removeClass('errorBorder');
            $(this).closest('.multiselect').find('.dropvalue').attr('rel', rel).addClass('active');
            $(this).closest('.multiselect').find('.dropvalue').html($(this).html());
            if ($(this).attr('flag') == "false")
                return;

            $( '.multiselect .dropup li.last' ).removeClass( 'selectSubTypes' );
            $(this).addClass( 'selectSubTypes' );

            $.ajax({
                url: '/ajax/user-creation/',
                type: 'post',
                data: {method: 'userTypesSubtypes', token: token, 'performerProfileId': rel.split(',')[1]},
                success: function(resp) {
                    // check save action
                    eval('var respObj = ' + resp);
                    if (respObj.status) {
                        $('.typesSubtypes').html();
                        $('#newUserRegisterStepsBody').fadeIn(1500);
                        $('#errorBox').html($.trim(respObj.msg)).show();
                        return false;
                    } else {
                        $('.typesSubtypes').html();
                        $('.typesSubtypes').html(respObj.html);
                    }
                }
            });
        });


    });

    $(window).bind("keyup", function(e) {
        if (e.witch == 27 || e.keyCode == 27) {
            setcookies("welcome", 1, 0, 604800);
            $('#firstTimeVisitLightBox').remove();
        }
    });
    $(window).load(function() {
        // open firstTimeVisitLightBox
        if (!getcookies('welcome')) {
            if ($('#firstTimeVisitLightBox').html()) {
                $('#firstTimeVisitLightBox').ipbox();
                // resize window
                $(window).trigger('resize');
            }
        }
        $('a#closeFirstTimeVisit').on('click', function() {
            setcookies("welcome", 1, 0, 604800);
            $(document).trigger('closeIpbox');
            $('#firstTimeVisitLightBox').remove();
        });

        // open the qyuki friend's list and show them in lightbox and ask from them for recommendation
        var userInviteSteps = $.trim($('input[name=userInviteSteps]').val());
        if (userInviteSteps == 1) {
            $('#inviteNotedDiv, #generalInfoDiv, #loginBox, #inviteNotedDiv #loginForm, #requestForInviteDiv', '#loginLightBox').hide();
            $('#yOurFrndsOnQyukiDiv', '#loginLightBox').show(function() {
                $('#loginLightBox').css('width', 'auto');
                // resize window
                $(window).trigger('resize');
            });
            $('#loginLightBox').ipbox({modal: true});
        } else if (userInviteSteps == 2) {
            $('#profileAndCoverPhotoDiv, #additionalInfoDiv, #generalInfoDiv', '#userPofileAndGeneralLightBox').hide();
            $('#profileSelectDiv', '#userPofileAndGeneralLightBox').show();
            $('#userPofileAndGeneralLightBox').ipbox({modal: true});
            // resize window
            $(window).trigger('resize');
        } else if (userInviteSteps == 100) {
            $('#processErrorLightBox').ipbox();
            // resize window
            $(window).trigger('resize');
        }
    });

    /*
     * User extra information area 
     */
    if ($('input[name=profileSelect]:checked').length > 0) {
        var proffileId = $('input[name=profileSelect]:checked').val();
        $('img.profileSelectedClass').hide();
        $('img.profileClass').show();

        $('#profileImg_' + proffileId).hide();
        $('#profileSelected_' + proffileId).show();
    }
    $(document).on('change', 'input[name=profileSelect]', function() {
        var $this = $(this);
        var proffileId = $this.val();

        $('.icon-greenTick').hide();
        $('img.profileSelectedClass').hide();
        $('img.profileClass').show();

        $('#profileImg_' + proffileId).hide();
        $('#profileSelected_' + proffileId).show();
        $('.icon-greenTick', $this.parent()).show();
    });
    $(document).on('click', 'input[name=profileSelectBtn]', function() {
        $this = $(this);
        if ($this.hasClass('disabled')) {
            console.log('Please wait your request is processing...');
            return false;
        }
        $('#subProfileSelectDivBody').html('');
        if ($('input[name=profileSelect]:checked').length == 0) {
            alert('Please selected profile !');
            return false;
        }
        var profileId = $('input[name=profileSelect]:checked').val();
        var inviteeSubProfileId = $(this).attr('rel');
        $this.addClass('disabled');
        $.ajax({
            url: '/ajax/admin/',
            type: 'post',
            data: {method: 'inviteeSubProfiles', id: profileId, subProfileId: inviteeSubProfileId},
            success: function(resp) {
                $this.removeClass('disabled');
                // check save action
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    alert(respObj.msg);
                    return false;
                } else {
                    $('#subProfileSelectDivBody').html(respObj.html);

                    $('#generalInfoDiv, #profileAndCoverPhotoDiv, #additionalInfoDiv, #profileSelectDiv', '#userPofileAndGeneralLightBox').hide();
                    //$( '#generalInfoDiv', '#userPofileAndGeneralLightBox' ).fadeIn( 500 );
                    $('#subProfileSelectDiv', '#userPofileAndGeneralLightBox').fadeIn(500);
                    // resize window
                    $(window).trigger('resize');
                }
            }
        });
    });

    $(document).on('change', 'input[name=subProfileSelect]', function() {
        var $this = $(this);
        var proffileId = $this.val();

        $('.icon-greenTick').hide();
        $('img.profileSelectedClass').hide();
        $('img.profileClass').show();

        $('#profileImg_' + proffileId).hide();
        $('#profileSelected_' + proffileId).show();
        $('.icon-greenTick', $this.parent()).show();
    });
    $(document).on('click', 'input[name=subProfileSelectBtn]', function() {
        if ($('input[name=subProfileSelect]:checked').length == 0) {
            alert('Please selected profile !');
            return false;
        }
        $('#profileAndCoverPhotoDiv, #additionalInfoDiv, #profileSelectDiv, #subProfileSelectDiv', '#userPofileAndGeneralLightBox').hide();
        $('#generalInfoDiv', '#userPofileAndGeneralLightBox').fadeIn(500);
        // resize window
        $(window).trigger('resize');
    });

    // user birth date picker
    $(".birthDatePicker").combodate({smartDays: true});
    $(document).on('blur', 'input[name=uLogin]', function() {
        var errorDiv = '#' + $(this).attr('name') + 'Error';
        if ($(errorDiv).html() == 'Unavailable!') {
            return false;
        }
        $(errorDiv).html('').hide();
        login = $.trim($(this).val());
        if (login == '') {
            $(errorDiv).html($(this).attr('rel')).show();
            return false;
        } else {
            if (login.length < 4) {
                $(errorDiv).html('Username must be more than three characters!').show();
                return false;
            }
            if (!isValidLogin(login)) {
                $(errorDiv).html('Invalid Username, only Alphanumeric characters and Underscore are allowed!').show();
                return false;
            }
        }
    });
    $(document).on('blur', 'input[name=confirmPassword]', function() {
        var errorDiv = '#' + $(this).attr('name') + 'Error';
        $(errorDiv).html('').hide();
        var userPass = $.trim($('input[name=uPassword]').val());
        var userConfirmPass = $.trim($(this).val());
        if (userPass == '') {
            $(errorDiv).html($('input[name=uPassword]').attr('rel')).show();
            return false;
        } else if (userConfirmPass == '') {
            $(errorDiv).html($(this).attr('rel')).show();
            return false;
        } else {
            if (userPass != userConfirmPass) {
                $(errorDiv).html('Password Mismatched!').show();
                return false;
            }
        }
    });
    $(document).on('blur', 'input[name=contactNo]', function() {
        var errorDiv = '#' + $(this).attr('name') + 'Error';
        $(errorDiv).html('').hide();
        var contactNo = $.trim($(this).val());
        if (contactNo == '') {
            $(errorDiv).html($(this).attr('rel')).show();
            return false;
        } else {
            var filter = /^[0-9]{10}$/;
            if (!filter.test(contactNo)) {
                $(errorDiv).html('Please enter valid 10 digit phone number !').show();
                return false;
            }
        }
    });

    $(document).on('click', 'a#generalNext', function() {
        var userFirstName = $.trim($('input[name=userFirstName]').val());
        if (userFirstName == '') {
            $('input[name=userFirstName]').focus();
            $('input[name=userFirstName]').next().html($('input[name=userFirstName]').attr('rel')).show();
            return false;
        }
        userLastName = $.trim($('input[name=userLastName]').val());
        // check user name
        $('#loginCheckMsg').text('').hide();
        login = $.trim($('input[name=uLogin]').val());
        if (login == '') {
            $('input[name=uLogin]').focus();
            $('input[name=uLogin]').next().html($('input[name=uLogin]').attr('rel')).show();
            return false;
        }
        if (login.length < 4) {
            $('input[name=uLogin]').val('').focus();
            $('input[name=uLogin]').next().html('Username must be aleast more than three character long!').show();
            return false;
        }
        if (!isValidLogin(login)) {
            $('input[name=uLogin]').next().html('Invalid Username, only Alphanumeric characters and Underscore are allowed!').show();
            $('input[name=uLogin]').focus();
            return false;
        }
        var loginCheckStatus = $.trim($('input[name=loginCheckStatus]').val());
        if (loginCheckStatus > 0) {
            $('input[name=uLogin]').next().html('Username already exist, Please try another !').show();
            $('input[name=uLogin]').val('').focus();
            return false;
        }
        // check password match
        var userPass = $.trim($('input[name=uPassword]').val());
        if (userPass == '') {
            $('#uPasswordError').html($('input[name=uPassword]').attr('rel')).show();
            $('input[name=uPassword]').focus();
            return false;
        }
        var userConfirmPass = $.trim($('input[name=confirmPassword]').val());
        if (userConfirmPass == '') {
            $('input[name=confirmPassword]').next().html($('input[name=confirmPassword]').attr('rel')).show();
            $('input[name=confirmPassword]').focus();
            return false;
        }
        if (userPass != userConfirmPass) {
            $('input[name=confirmPassword]').val('').focus();
            $('input[name=confirmPassword]').next().html('Password Missmatched').show();
            return false;
        }
        var country = $.trim($('select[name=uCountry]').val());
        var city = $.trim($('input[name=uCity]').val());
        if (city == '') {
            $('input[name=uCity]').next().html($('input[name=uCity]').attr('rel')).show();
            $('input[name=uCity]').focus();
            return false;
        }
        var birth = $.trim($('input[name=uBirth]').val());
        if (birth == '') {
            $('input[name=uBirth]').parent().next().html($('input[name=uBirth]').attr('rel')).show();
            $('input[name=uBirth]').focus();
            return false;
        }
        var gender = $.trim($('input[name=gender]:checked').val());
        var contactNo = $.trim($('input[name=contactNo]').val());
        if (contactNo == '') {
            $('input[name=contactNo]').next().html($('input[name=contactNo]').attr('rel')).show();
            $('input[name=contactNo]').focus();
            return false;
        } else {
            var filter = /^[0-9]{10}$/;
            if (!filter.test(contactNo)) {
                $('input[name=contactNo]').next().html('Please enter valid 10 digit phone number !').show();
                $('input[name=contactNo]').val('').focus();
                return false;
            }
        }
        var description = $.trim($('textarea[name=aboutUserDesc]').val());
        if (description == '') {
            $('textarea[name=aboutUserDesc]').next().html($('textarea[name=aboutUserDesc]').attr('rel')).show();
            $('textarea[name=aboutUserDesc]').focus();
            return false;
        }
        var userInviteId = $.trim($('input[name=userInviteId]').val());
        if (userInviteId < 0) {
            alert("There is no invitation exist, You can't create profile !");
            return false;
        }
        var profileId = $('input[name=profileSelect]:checked').val();
        var subProfileId = $('input[name=subProfileSelect]:checked').val();
        var draftUserId = $.trim($('input[name=draftUserId]').val());
        $.ajax({
            url: '/ajax/invite/',
            type: 'post',
            data: {
                method: 'createUserByInvitation', draftUserId: draftUserId,
                firstName: userFirstName, lastName: userLastName, login: login,
                password: userPass, confirmPassword: userConfirmPass,
                profileId: profileId, subProfileId: subProfileId, userInviteId: userInviteId,
                country: country, city: city, birth: birth, contactNo: contactNo, gender: gender,
                description: description
            }, success: function(resp) {
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    alert($.trim(respObj.message));
                    return false;
                } else {
                    // hide userPofileAndGeneralLightBox and show next lightbox
                    $('input[name=newUserId]').val(respObj.newUserId);


                    var profiles = respObj.profiles;
                    $('select[name=userProfileId] option').remove();
                    for (var n in profiles) {
                        if (profiles[n].selected == 'selected') {
                            $('<option selected="selected" value="' + profiles[n].value + '">' + profiles[n].text + '</option>').appendTo($('select[name=userProfileId]'));
                        } else {
                            $('<option value="' + profiles[n].value + '">' + profiles[n].text + '</option>').appendTo($('select[name=userProfileId]'));
                        }
                    }
                    var isSubProfilePerformer = false;
                    var subProfiles = respObj.subProfiles;
                    $('select[name=userSubProfileId] option').remove();
                    for (var n in subProfiles) {
                        if (subProfiles[n].selected == 'selected') {
                            if (subProfiles[n].value == 1) {
                                isSubProfilePerformer = true;
                            }
                            $('<option selected="selected" value="' + subProfiles[n].value + '">' + subProfiles[n].text + '</option>').appendTo($('select[name=userSubProfileId]'));
                        } else {
                            $('<option value="' + subProfiles[n].value + '">' + subProfiles[n].text + '</option>').appendTo($('select[name=userSubProfileId]'));
                        }
                    }

                    // show/hide is subprofile is performer or not
                    if (isSubProfilePerformer) {
                        $('div#subProfileTypeDiv, div#subProfileSubTypeDiv').fadeIn(300);
                    } else {
                        $('div#subProfileTypeDiv, div#subProfileSubTypeDiv').fadeOut(300);
                    }

                    var types = respObj.types;
                    $('select[name=userSubProfileType] option').remove();
                    for (var n in types) {
                        if (types[n].selected == 'selected') {
                            $('<option selected="selected" value="' + types[n].value + '">' + types[n].text + '</option>').appendTo($('select[name=userSubProfileType]'));
                        } else {
                            $('<option value="' + types[n].value + '">' + types[n].text + '</option>').appendTo($('select[name=userSubProfileType]'));
                        }
                    }

                    var subtypes = respObj.subtypes;
                    $('select[name=userSubProfileSubType] option').remove();
                    for (var n in subtypes) {
                        if (subtypes[n].selected == 'selected') {
                            $('<option selected="selected" value="' + subtypes[n].value + '">' + subtypes[n].text + '</option>').appendTo($('select[name=userSubProfileSubType]'));
                        } else {
                            $('<option value="' + subtypes[n].value + '">' + subtypes[n].text + '</option>').appendTo($('select[name=userSubProfileSubType]'));
                        }
                    }

                    var experiences = respObj.experiences;
                    $('select[name=userExperience] option').remove();
                    for (var n in experiences) {
                        if (experiences[n].selected == 'selected') {
                            $('<option selected="selected" value="' + experiences[n].value + '">' + experiences[n].text + '</option>').appendTo($('select[name=userExperience]'));
                        } else {
                            $('<option value="' + experiences[n].value + '">' + experiences[n].text + '</option>').appendTo($('select[name=userExperience]'));
                        }
                    }

                    var performances = respObj.performances;
                    $('select[name=livePerformanceExp] option').remove();
                    for (var n in performances) {
                        if (performances[n].selected == 'selected') {
                            $('<option selected="selected" value="' + performances[n].value + '">' + performances[n].text + '</option>').appendTo($('select[name=livePerformanceExp]'));
                        } else {
                            $('<option value="' + performances[n].value + '">' + performances[n].text + '</option>').appendTo($('select[name=livePerformanceExp]'));
                        }
                    }

                    $('input[name=userInviteSteps]').val(3);
                    $('#userPofileAndGeneralLightBox').hide();
                    $('#creationProcessDiv, #profileAndCoverPhotoDiv, #endProfileCreationDiv', '#extraUserInfoLightBox').hide();
                    //$( '#userAllExtraInfoDiv, #additionalInfoDiv', '#extraUserInfoLightBox' ).show();
                    $('#userAllExtraInfoDiv, #additionalInfoDiv', '#extraUserInfoLightBox').fadeIn(500);
                    $('#extraUserInfoLightBox').ipbox({modal: true});
                    // resize window
                    $(window).trigger('resize');
                }
            }
        });
    });

    // on select of user profile fill the user subprofle
    $(document).on('change', 'select[name=userProfileId]', function() {
        $this = $(this);
        var profileId = $this.val();

        $('select[name=userSubProfileId] option').remove();
        $('<option value="0">Please wait...</option>').appendTo($('select[name=userSubProfileId]'));

        $('select[name=userSubProfileType] option').remove();
        $('<option value="0">Please wait...</option>').appendTo($('select[name=userSubProfileType]'));

        $('select[name=userSubProfileSubType] option').remove();
        $('<option value="0">Please wait...</option>').appendTo($('select[name=userSubProfileSubType]'));

        $.ajax({
            url: '/ajax/admin/',
            type: 'post',
            data: {method: 'getSubProfiles', id: profileId, type: 'first'},
            success: function(resp) {
                // check save action
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    alert(respObj.msg);
                    return false;
                } else {
                    eval('var respObj = ' + resp);
                    var profiles = respObj.profiles;
                    $('select[name=userSubProfileId] option').remove();
                    for (var n in profiles) {
                        $('<option value="' + profiles[n].value + '">' + profiles[n].text + '</option>').appendTo($('select[name=userSubProfileId]'));
                    }

                    var types = respObj.types;
                    $('select[name=userSubProfileType] option').remove();
                    for (var n in types) {
                        $('<option value="' + types[n].value + '">' + types[n].text + '</option>').appendTo($('select[name=userSubProfileType]'));
                    }

                    var subtypes = respObj.subtypes;
                    $('select[name=userSubProfileSubType] option').remove();
                    for (var n in subtypes) {
                        $('<option value="' + subtypes[n].value + '">' + subtypes[n].text + '</option>').appendTo($('select[name=userSubProfileSubType]'));
                    }
                }
            }
        });
    });
    // on select of user sub profile fill the user subprofle types
    $(document).on('change', 'select[name=userSubProfileId]', function() {
        $this = $(this);
        var profileId = $this.val();
        // show/hide is subprofile is performer or not 
        if (profileId == 1) {
            $('div#subProfileTypeDiv, div#subProfileSubTypeDiv').fadeIn(300);
        } else {
            $('div#subProfileTypeDiv, div#subProfileSubTypeDiv').fadeOut(300);
        }

        $('select[name=userSubProfileType] option').remove();
        $('<option value="0">Please wait...</option>').appendTo($('select[name=userSubProfileType]'));

        $('select[name=userSubProfileSubType] option').remove();
        $('<option value="0">Please wait...</option>').appendTo($('select[name=userSubProfileSubType]'));

        $.ajax({
            url: '/ajax/admin/',
            type: 'post',
            data: {method: 'getSubProfiles', id: profileId, type: 'first'},
            success: function(resp) {
                // check save action
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    alert(respObj.msg);
                    return false;
                } else {
                    eval('var respObj = ' + resp);
                    var profiles = respObj.profiles;
                    $('select[name=userSubProfileType] option').remove();
                    for (var n in profiles) {
                        $('<option value="' + profiles[n].value + '">' + profiles[n].text + '</option>').appendTo($('select[name=userSubProfileType]'));
                    }

                    var types = respObj.types;
                    $('select[name=userSubProfileSubType] option').remove();
                    for (var n in types) {
                        $('<option value="' + types[n].value + '">' + types[n].text + '</option>').appendTo($('select[name=userSubProfileSubType]'));
                    }
                }
            }
        });
    });

    // on select of user subprofle type fill the user subprofleSubtypes
    $(document).on('change', 'select[name=userSubProfileType]', function() {
        $this = $(this);
        var profileId = $this.val();
        $('select[name=userSubProfileSubType] option').remove();
        $('<option value="0">Please wait...</option>').appendTo($('select[name=userSubProfileSubType]'));
        $.ajax({
            url: '/ajax/admin/',
            type: 'post',
            data: {method: 'getSubProfiles', id: profileId},
            success: function(resp) {
                // check save action
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    alert(respObj.msg);
                    return false;
                } else {
                    eval('var respObj = ' + resp);
                    var profiles = respObj.profiles;
                    $('select[name=userSubProfileSubType] option').remove();
                    for (var n in profiles) {
                        $('<option value="' + profiles[n].value + '">' + profiles[n].text + '</option>').appendTo($('select[name=userSubProfileSubType]'));
                    }
                }
            }
        });
    });

    /*
     * user add step 3 Area
     */
    // skip additional info area and show user profile/cover image and crop area  
    $(document).on('click', 'a.additionalInfoSkip', function() {
        $('#additionalInfoDiv', '#extraUserInfoLightBox').hide();
        $('#profileAndCoverPhotoDiv', '#extraUserInfoLightBox').show();
        return false;
    });
    // add additional info area and show user profile/cover image and crop area  
    $(document).on('click', 'a.additionalInfoNext', function() {
        var newUserId = $.trim($('input[name=newUserId]').val());
        userProfileId = $('select[name=userProfileId]').val();
        userSubProfileId = $('select[name=userSubProfileId]').val();
        userSubProfileType = $('select[name=userSubProfileType]').val();
        userSubProfileSubType = $('select[name=userSubProfileSubType]').val();
        userExperience = $('select[name=userExperience]').val();
        livePerformanceExp = $('select[name=livePerformanceExp]').val();
        $.ajax({
            url: '/ajax/invite/',
            type: 'post',
            data: {
                method: 'saveUserAdditionalInfo', userId: newUserId,
                profileId: userProfileId, subProfileId: userSubProfileId,
                subProfileType: userSubProfileType, subProfileSubType: userSubProfileSubType,
                userExperience: userExperience, livePerformanceExp: livePerformanceExp
            },
            success: function(resp) {
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    alert($.trim(respObj.message));
                    return false;
                } else {
                    $('#additionalInfoDiv', '#extraUserInfoLightBox').hide();
                    //$( '#profileAndCoverPhotoDiv', '#extraUserInfoLightBox' ).show();
                    $('#profileAndCoverPhotoDiv', '#extraUserInfoLightBox').fadeIn(1000);
                    // resize window
                    $(window).trigger('resize');
                    return false;
                }
            }
        });
    });
    // move user to create new creation area 
    $(document).on('click', 'a.profileAndCoverPhotoNext, a.profileAndCoverPhotoSkip', function() {
        $('#userAllExtraInfoDiv, #lastUserCreationStepDiv, #uploadContentAbtDiv, #profileAndCoverPhotoDiv', '#extraUserInfoLightBox').hide();
        //$( '#uploadContentDiv, #creationProcessDiv', '#extraUserInfoLightBox' ).show();
        $('#uploadContentDiv, #creationProcessDiv', '#extraUserInfoLightBox').fadeIn(1000);
        // resize window
        $(window).trigger('resize');
        return false;
    });

    /* end of user create step 3 area */

    /* Create new creation Area and user add last step */
    // fix the creation title character limit

    $(document).on('keyup propertychange paste', 'input[name=creationTitle]', function() {
        setCharacterLimit($('input[name=creationTitle]'), 'titleCharacterleft');
    });

    $(document).on('keyup propertychange paste', 'textarea[name=aboutUserDesc]', function() {
        setCharacterLimit($('textarea[name=aboutUserDesc]'), 'aboutUserDescLimit');
    });

    $(document).on('keyup propertychange paste', 'textarea[name=awards]', function() {
        setCharacterLimit($('textarea[name=awards]'), 'awardsLimit');
    });


    function setCharacterLimit($this, id) {
        var comment = $this.val();
        var totalLength = $this.attr('length');
        var charLength = comment.length;
        charLength = totalLength - charLength;
        if (charLength > -1) {
            $('#' + id).html(charLength + ' Character Left');
        } else {
            $this.val(comment.substring(0, totalLength));
        }
    }
    // add post as a creation while user in login state 
    $(document).on('click', 'a#addCreation', function() {
        // reset creation steps
        $('input[name=newCreationId]').val('');
        $('input[name=newMediaId]').val('0');
        $('select[name=categoryId]').val('');
        $('input[name=creationTitle]').val('');
        $('textarea[name=creationDesc]').val('');
        $('input[name=creationTags]').val('');
        $('input[name=newMediaType]').val('');
        $('input[name=youtubeUrl]').val('');
        $('a#cropCreationCoverImg').parent().hide();
        $('span.creationProjectTitle').text('');
        $('#creationProjectId').val(0);
        $('#addCreationCoverImgRight').attr('src', '/images/newBigUpload.png').removeClass('loading');

        // reset lightbox forms
        $('#uploadContentCoverImgDiv, #userAllExtraInfoDiv, #lastUserCreationStepDiv, #uploadContentAbtDiv, #profileAndCoverPhotoDiv, #additionalInfoDiv', '#extraUserInfoLightBox').hide();
        $('#uploadContentFinishedDiv, #uploadContentDiv, #creationProcessDiv', '#extraUserInfoLightBox').hide();
        // open lightbox
        $('#extraUserInfoLightBox').ipbox({modal: true});
        $('#uploadContentDiv, #creationProcessDiv', '#extraUserInfoLightBox').fadeIn(500);
        return false;
    });
    // add post for project when post are created via project section
    $(document).on('click', 'input.addProjectCreation', function() {
        $('#userAllExtraInfoDiv, #lastUserCreationStepDiv, #uploadContentAbtDiv, #profileAndCoverPhotoDiv', '#extraUserInfoLightBox').hide();
        $('#uploadContentFinishedDiv, #uploadContentDiv, #creationProcessDiv', '#extraUserInfoLightBox').hide();
        // reset creation steps
        $('input[name=newCreationId]').val('');
        $('input[name=newMediaId]').val('0');
        $('select[name=categoryId]').val('');
        $('input[name=creationTitle]').val('');
        $('textarea[name=creationDesc]').val('');
        $('input[name=creationTags]').val('');
        $('input[name=newMediaType]').val('');
        $('input[name=youtubeUrl]').val('');
        $('a#cropCreationCoverImg').parent().hide();
        $('span.creationProjectTitle').text('');
        $('#creationProjectId').val(0);
        $('#addCreationCoverImgRight').attr('src', '/images/newBigUpload.png').removeClass('loading');

        setCharacterLimit($('input[name=creationTitle]'), 'titleCharacterleft');

        $('span.creationProjectTitle').text($.trim($(this).attr('projectTitle')));
        $('#creationProjectId').val($.trim($(this).attr('rel')));

        $('#extraUserInfoLightBox').ipbox();
        $('#uploadContentDiv, #creationProcessDiv', '#extraUserInfoLightBox').fadeIn(500);
        return false;
    });

    // include new file uploader code comes here...
    function openMediaFilepicker() {
        var bucketVideoPath = $.trim($('#bucketVideoPath').val());

        filepicker.setKey('AqBAT8SybQvuPMkFzZ6FJz');
        filepicker.pickAndStore(
                {mimetype: ['video/*', 'audio/*'], folders: true, multiple: false, maxFiles: 1},
        {location: 'S3', access: 'private', path: bucketVideoPath},
        function(success) { // on success
            //console.log( success );
            $.each(success, function(index, file) {
                $.ajax({
                    url: '/ajax/invite/', type: 'post',
                    data: {
                        method: 'saveCreationMediaData', name: file.filename,
                        s3Key: file.key, mimetype: file.mimetype, size: file.size
                    },
                    success: function(resp) {
                        // check save action
                        eval('var respObj = ' + resp);
                        if (respObj.status) {
                            alert(respObj.msg);
                            $('input[name=newMediaId]').val('0');
                            $('input[name=newMediaType]').val('');
                        } else {
                            // set media type
                            $('input[name=newMediaType]').val(respObj.fileType);
                            // set media id
                            $('input[name=newMediaId]').val(respObj.mediaId);
                            // show next step
                            $('#uploadContentDiv, #profileAndCoverPhotoDiv, #additionalInfoDiv', '#extraUserInfoLightBox').hide();
                            $('#uploadContentAbtDiv', '#extraUserInfoLightBox').show();
                        }
                    }
                });
            });
        }, function(failure) { // on failure
            console.log(failure);
            $('input[name=newMediaId]').val('');
            $('input[name=newMediaType]').val('');
        }
        );
    }
    // upload creation media file div click
    $('#uploadMediaFileDiv').click(function() {
        openMediaFilepicker();
    });
    // create new creation step 1 ( upload any media file )
    $(document).on('blur', 'input[name=youtubeUrl]', function() {
        $(this).next().html('').hide();
        youtubeUrl = $.trim($(this).val());
        if (youtubeUrl == '') {
            //$( this ).next().html( $( this ).attr( 'rel' ) ).show();
            return false;
        } else {
            youtubeUrl = youtubeUrl.replace('http://', '');
            youtubeUrl = youtubeUrl.replace('https://', '');
            youtubeUrl = youtubeUrl.replace('www.', '');
            youtubeUrl = 'http://www.' + youtubeUrl;
            if (!isValidYoutubeUrl(youtubeUrl)) {
                $(this).val('');
                $(this).next().html('Enter valid Youtube URL!').show();
                return false;
            }
        }
    });

    $(document).on('blur', '#creationProcessDiv input[name=creationTitle], #creationProcessDiv select[name=categoryId]', function() {
        $(this).next().html('').hide();
        if ($.trim($(this).val()) == '') {
            $(this).next().html($(this).attr('rel')).show();
            return false;
        }
    });

    $(document).on('click', 'a.uploadContentNext', function() {
        $('#addCreationErrorMsg').text('').hide();
        $this = $(this);
        if ($this.hasClass('disabled')) {
            console.log('Please wait your request is processing...');
            return false;
        }
        $('div.inputError').html('');
        var newMediaId = $.trim($('input[name=newMediaId]').val());
        newMediaId = newMediaId == '' ? 0 : newMediaId;
        var youtubeUrl = $.trim($('input[name=youtubeUrl]').val());
        if (!(youtubeUrl != '' || newMediaId > 0)) {
            $('input[name=youtubeUrl]').next().html('Please upload audio/video media or enter youtube video url !').show();
            return false;
        }
        if (youtubeUrl != '') {
            youtubeUrl = youtubeUrl.replace('http://', '');
            youtubeUrl = youtubeUrl.replace('https://', '');
            youtubeUrl = youtubeUrl.replace('www.', '');
            youtubeUrl = 'http://www.' + youtubeUrl;
            if (!isValidYoutubeUrl(youtubeUrl)) {
                youtubeUrl = $.trim($('input[name=youtubeUrl]').val());
                $('input[name=youtubeUrl]').val('').focus();
                $('input[name=youtubeUrl]').next().html('Enter valid Youtube URL!').show();
            } else {
                $this.addClass('disabled');
                $.ajax({
                    url: '/ajax/invite/', type: 'post',
                    data: {
                        method: 'saveCreationYoutubeUrlData', youtubeUrl: youtubeUrl
                    },
                    success: function(resp) {
                        $this.removeClass('disabled');
                        // check save action
                        eval('var respObj = ' + resp);
                        if (respObj.status) {
                            alert(respObj.message);
                            $('input[name=newMediaId]').val('0');
                            $('input[name=newMediaType]').val('');
                        } else {
                            // set media type
                            $('input[name=newMediaType]').val(respObj.fileType);
                            // set media id
                            $('input[name=newMediaId]').val(respObj.mediaId);
                            // show next step
                            $('#uploadContentDiv, #profileAndCoverPhotoDiv, #additionalInfoDiv', '#extraUserInfoLightBox').hide();
                            //$( '#uploadContentAbtDiv', '#extraUserInfoLightBox' ).show();
                            $('#uploadContentAbtDiv', '#extraUserInfoLightBox').fadeIn(500);
                            // resize window 
                            $(window).trigger('resize');
                        }
                    }
                });
            }
        } else {
            var newMediaId = $.trim($('input[name=newMediaId]').val());
            if (newMediaId == 0) {
                $('#uploadMediaFileDiv').trigger('click');
            } else if (newMediaId == '') {
                $('#uploadMediaFileDiv').trigger('click');
            }
            $this.removeClass('disabled');
        }
        return false;
    });

    // create new creation step 2 ( final add new creation step and complesory step )
    $(document).on('click', 'a.uploadContentAbtNext', function() {
        $this = $(this);
        if ($this.hasClass('disabled')) {
            console.log('Please wait your request is processing...');
            return false;
        }
        // check if user added or not
        var newUserId = $.trim($('input[name=newUserId]').val());
        if (newUserId <= 0) {
            alert('Unable to create creation as there is no userId found in this step ');
            return false;
        }
        // check for title
        var title = $.trim($('input[name=creationTitle]').val());
        if (title == '') {
            $('input[name=creationTitle]').focus();
            $('input[name=creationTitle]').next().html($('input[name=creationTitle]').attr('rel')).show();
            return false;
        }
        // check for category selected or not
        var categoryName = $('select[name=categoryId]').find(":selected").text();
        var categoryId = $.trim($('select[name=categoryId]').val());
        if ( categoryId == '' ) {
            $('select[name=categoryId]').focus();
            $('select[name=categoryId]').next().html($('select[name=categoryId]').attr('rel')).show();
            return false;
        }
        // get description
        var desc = $.trim($('textarea[name=creationDesc]').val());
        // get tags
        var tags = $.trim($('input[name=creationTags]').val());
        // fetch media id
        var mediaId = $.trim($('input[name=newMediaId]').val());
        // get uploaded media type
        var fileType = $.trim($('input[name=newMediaType]').val());
        // get project id if present
        var projectId = $.trim($('input[name=creationProjectId]').val());
        $this.addClass('disabled');
        $.ajax({
            url: '/ajax/invite/',
            type: 'post',
            data: {
                method: 'addCreationWithMedia', title: title,
                categoryId: categoryId, description: desc, tags: tags,
                mediaId: mediaId, type: fileType, newUserId: newUserId,
                projectId: projectId
            },
            success: function(resp) {
                $this.removeClass('disabled');
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    $('input[name=newCreationId]').val(0);
                    //alert( $.trim( respObj.message ) );
                    $('#addCreationErrorMsg').text(respObj.message).show();
                    return false;
                } else {
                    $('input[name=newCreationId]').val(respObj.creationId);
                    $('img#coverUserImg').attr('src', respObj.coverUserImg);

                    var newTitle = title.length > 30 ? title.substring( 0,28 ) + '..': title;
                    var newDesc = desc.length > 30 ? desc.substring( 0, 28 ) + '..' : desc;

                    $('div#newCategory').html(categoryName);
                    $('div#newTitle').html( newTitle );
                    $('div#newDesc').html( newDesc );

                    $('#uploadContentAbtDiv, #uploadContentDiv, #profileAndCoverPhotoDiv, #additionalInfoDiv', '#extraUserInfoLightBox').hide();
                    //$( '#uploadContentCoverImgDiv', '#extraUserInfoLightBox' ).show();
                    $('#uploadContentCoverImgDiv', '#extraUserInfoLightBox').fadeIn(500);
                    // resize window 
                    $(window).trigger('resize');
                    return false;
                }
            }
        });
    });

    $(document).on('click', 'a.finishCreationSteps', function() {
        $('a.uploadContentNext').removeClass('disabled');
        $('#uploadContentCoverImgDiv, #uploadContentAbtDiv, #uploadContentDiv, #profileAndCoverPhotoDiv, #additionalInfoDiv', '#extraUserInfoLightBox').hide();
        $('#uploadContentFinishedDiv').ipbox({modal: true});
        // resize window 
        $(window).trigger('resize');
        setTimeout(function() {
            $(document).trigger('closeIpbox');
        }, 3000);
    });

    /* upload cover image area  */
    // include new file uploader code comes here...
    function openCreationCoverImgFilepicker() {
        var bucketImagePath = $.trim($('#bucketImagePath').val());
        $('#addCreationCoverImgRightSpinner').show();
        filepicker.pickAndStore(
                {mimetype: 'image/*', folders: true, multiple: false, maxFiles: 1},
        {location: 'S3', access: 'public', path: bucketImagePath},
        function(success) { // on success
            //console.log( success );
            $.each(success, function(index, file) {
                $('#addCreationCoverImgRightSpinner').hide();

                var newImagePath = $.trim($('input#imagePublicLocation').val()) + file.key;
                console.log(newImagePath);

                $('#addCreationCoverImgRight').attr('src', newImagePath + '?ts=' + parseInt(Math.random() * 10000)).removeClass('loading');
                $('a#cropCreationCoverImg').parent().show();

                launchAvairyEditor('addCreationCoverImgRight');
            });
        }, function(failure) { // on failure
            console.log(failure);
            $('#userProfileImageSpinner, #userCoverImageSpinner, #addCreationCoverImgRightSpinner').hide();
            var uploadImgIcon = $('#addCreationCoverImgRight').attr('original');
            $('#addCreationCoverImgRight').attr('src', uploadImgIcon);//.removeClass( 'loading' );
        }
        );
    }

    $(document).on('click', 'a.bigUploadIcon', function() {
        //$( 'input[name=uploadImgFile]' ).click();
        var newMediaId = $.trim($('input[name=newMediaId]').val());
        if (newMediaId == '' || newMediaId == '0') {
            alert('No media uploaded !');
            return false;
        }
        var newCreationId = $.trim($('input[name=newCreationId]').val());
        if (newCreationId == '' || newCreationId == '0') {
            alert('No creation found !');
            return false;
        }
        openCreationCoverImgFilepicker();
    });

    $(document).on('click', 'a.uploadContentCoverImgPrev', function() {
        // reset creation steps
        $('a.uploadContentNext').removeClass('disabled');
        $('input[name=newCreationId]').val('');
        $('input[name=newMediaId]').val('0');
        $('select[name=categoryId]').val('');
        $('input[name=creationTitle]').val('');
        $('textarea[name=creationDesc]').val('');
        $('input[name=creationTags]').val('');
        $('input[name=newMediaType]').val('');
        $('input[name=youtubeUrl]').val('');
        $('a#cropCreationCoverImg').parent().hide();

        $('#addCreationCoverImgRight').attr('src', '/images/newBigUpload.png').removeClass('loading');

        $('#uploadContentCoverImgDiv, #uploadContentAbtDiv, #lastUserCreationStepDiv, #profileAndCoverPhotoDiv, #additionalInfoDiv', '#extraUserInfoLightBox').hide();
        //$( '#uploadContentDiv', '#extraUserInfoLightBox' ).show();
        $('#uploadContentDiv', '#extraUserInfoLightBox').fadeIn(500);
        // resize window 
        $(window).trigger('resize');
        return false;
    });

    $(document).on('click', 'a.uploadContentCoverImgNxt', function() {
        $.ajax({
            url: '/ajax/invite/',
            type: 'post',
            data: {method: 'autoLoginNewUser'},
            success: function(resp) {
                eval('var respObj = ' + resp);
                if (respObj.status) {
                    alert($.trim(respObj.message));
                    return false;
                } else {
                    window.location = respObj.loginUrl;
                    return false;
                    /*$( '#uploadContentCoverImgDiv, #uploadContentAbtDiv, #uploadContentDiv, #profileAndCoverPhotoDiv, #additionalInfoDiv', '#extraUserInfoLightBox' ).hide();
                     $( '#lastUserCreationStepDiv', '#extraUserInfoLightBox' ).show();
                     return false;*/
                }
            }
        });
    });

    // auto login user at end of the step
    $(document).on('click', 'a#autoLoginNewUser', function() {
        $(document).trigger('closeIpbox');
        /*var newUserId = $.trim( $( 'input[name=newUserId]' ).val() );
         $.ajax( {
         url : '/ajax/invite/',
         type : 'post',
         data : { method : 'autoLoginNewUser', userId : newUserId },
         success : function( resp ) {
         eval( 'var respObj = ' + resp );
         if( respObj.status ){
         alert( $.trim( respObj.message ) );
         return false;
         }else{
         window.location = respObj.loginUrl;
         return false;
         }
         }
         });*/
    });
    /* End of create new creation area and user add last step */

});


		